package day06.concurrent03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock 线程间通信机制
 */
public class Demo06 {
    static String name = "小明";
    static String gender = "男";
    static Lock lock = new ReentrantLock();
    static Condition cond = lock.newCondition();

    public static void main(String[] args) {
        //cond.await();//进入阻塞状态
        //cond.signal();//唤醒在cond上进入阻塞状态的任一线程
        //cond.signalAll();//唤醒再cond上进入阻塞状态的所有线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        lock.lock();
                        System.out.println(name+"#"+gender);
                        cond.signal();
                        cond.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        lock.lock();
                        if("小明".equals(name)){
                            name = "小花";
                            gender = "女";
                        }else{
                            name = "小明";
                            gender = "男";
                        }
                        cond.signal();
                        cond.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }).start();
    }
}
